package com.cys.dm.rest.service;

import com.cys.dm.client.base.DmAreaClient;
import com.cys.dm.client.base.DmImageClient;
import com.cys.dm.client.item.DmCinemaClient;
import com.cys.dm.client.item.DmItemClient;
import com.cys.dm.entity.base.DmArea;
import com.cys.dm.entity.base.DmImage;
import com.cys.dm.entity.item.DmCinema;
import com.cys.dm.entity.item.DmItem;
import com.cys.dm.entity.item.DmItemType;
import com.cys.dm.vo.dmes.DmItemRowsEs;
import com.cys.dm.vo.dmitem.DmItemRowsPageResponse;
import com.cys.dm.vo.dmitem.DmItemTypeResponse;
import com.cys.dm.vo.itemlist.QueryItemList;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DmAreaService {
    @Autowired
    private DmAreaClient dmAreaClient;
    @Autowired
    private DmItemClient dmItemClient;
    @Autowired
    private DmImageClient dmImageClient;
    @Autowired
    private DmCinemaClient dmCinemaClient;
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    /**
     * 城市列表
     * @return 所有城市
     */
    @PostMapping(path = "/queryCityList")
    public List<DmArea> dmAreaList(){
        return dmAreaClient.dmAreaList();
    }

    /**
     * 这里查询为一级标题
     * @return 查询父级标题
     */
    @PostMapping(path = "/queryItemType")
    public List<DmItemTypeResponse> queryItemType(Map<String,Long> map){
        List<DmItemTypeResponse> list = new ArrayList<>();
        Long id = 0L;
        for (String item : map.keySet()){
            if (item.equals("parent")) {
                id = Long.valueOf(String.valueOf(map.get("parent"))).longValue();
            }
            if (item.equals("param")) {
                id = Long.valueOf(String.valueOf(map.get("param"))).longValue();
            }
        }
        List<DmItemType> oneItemType = dmItemClient.dmItemTypeList(id);
        oneItemType.forEach(item ->{
            DmItemTypeResponse itemTypeResponse = new DmItemTypeResponse();
            BeanUtils.copyProperties(item,itemTypeResponse);
            list.add(itemTypeResponse);
        });

        return list;
    }

    /**
     * 根据一二级标题查商品
     * @param params
     * @return
     */
    @PostMapping(path = "/querygoodsinfos")
    public DmItemRowsPageResponse<DmItemRowsEs> querygoodsinfos(Map<String,String> params){
        //关键字
        String keyword = params.get("keyword");
        //当前页
        Integer currentPage = Integer.parseInt(params.get("currentPage"));
        //每页显示max数据数量
        Integer pageSize = Integer.parseInt(params.get("pageSize"));
        //城市ID
        Integer areaId =  Integer.parseInt(params.get("areaId"));
        //商品一级分类
        Integer itemTypeId1 = Integer.parseInt(params.get("itemTypeId1"));
        //商品一级分类
        Integer itemTypeId2 = Integer.parseInt(params.get("itemTypeId2"));
        if (itemTypeId1==null){
            itemTypeId1 = 1;
        }
        if (itemTypeId2==null){
            itemTypeId2 = 1;
        }
        //热门推荐/最近开场/最新上架
        String sort = params.get("sort").toString();

        //开始时间
        String startTime = null;
        if (!"".equals(params.get("startTime"))) {
            startTime = params.get("startTime").toString();
        }
        String endTime = null;
        //结束时间
        if (!"".equals(params.get("endTime"))) {
            endTime = params.get("endTime").toString();
        }

        String preTag = "<span style='color:red'>";
        String postTag = "</span>";

        BoolQueryBuilder boolQueryBuilder=QueryBuilders.boolQuery();
        //关键字查询
        if (!"".equals(keyword) && null != keyword) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("itemname", keyword));
        }
        //城市查询
        if (areaId != 0) {
            String areaName = dmAreaClient.findById(areaId).getName();
            boolQueryBuilder.must(QueryBuilders.matchQuery("areaname", areaName));
        }
        if (itemTypeId1 != 0) {
            //一级分类
            boolQueryBuilder.must(QueryBuilders.termQuery("itemtype1id", itemTypeId1));
        }
        if (itemTypeId2 != 0) {
            //二级分类
            boolQueryBuilder.must(QueryBuilders.termQuery("itemtype2id", itemTypeId2));
        }
        if (startTime != null && endTime != null) {
            //开始时间
            boolQueryBuilder.must(QueryBuilders.rangeQuery("starttime").gte(startTime).lte(endTime));
        }

        //排序字段
        SortBuilder sortBuilder = null;
        //标识是否排序
        boolean flagSort = false;
        //tabs的条件
        if ("".equals(sort) || sort == null) {
            //默认热门推荐
            boolQueryBuilder.must(QueryBuilders.termQuery("isrecommend", 1));
        } else {
            switch (sort) {
                //推荐
                case "recommend":
                    boolQueryBuilder.must(QueryBuilders.termQuery("isrecommend", 1));
                    break;
                //最近开场
                case "recentShow":
                    //时间大于现在 且 升序排序
                    boolQueryBuilder.must(QueryBuilders.rangeQuery("starttime").gt(LocalDateTime.now()));
                    sortBuilder = SortBuilders.fieldSort("starttime").order(SortOrder.ASC);
                    //标识启用具有排序的构建对象
                    flagSort = true;
                    break;
                //最新上架
                case "recentSell":
                    // 今天-10t >= 最新上架 <= 今天
                    //降序
                    LocalDate start = LocalDate.now().minusDays(10L);
                    boolQueryBuilder.must(QueryBuilders.rangeQuery("starttime").gte(start).lte(LocalDate.now()));
                    sortBuilder = SortBuilders.fieldSort("starttime").order(SortOrder.DESC);
                    flagSort = true;
                    break;
            }
        }

        //封装条件
        NativeSearchQuery query = null;
        if (flagSort){
            query = new NativeSearchQueryBuilder()
                    .withQuery(boolQueryBuilder)
                    .withHighlightFields(
                            new HighlightBuilder.Field("itemname")
                    )
                    .withHighlightBuilder(new HighlightBuilder().preTags(preTag).postTags(postTag))
                    .withPageable(PageRequest.of(currentPage - 1, pageSize))
                    //排序
                    .withSort(sortBuilder)
                    .build();
        }else{
            query = new NativeSearchQueryBuilder()
                    .withQuery(boolQueryBuilder)
                    .withHighlightFields(
                            new HighlightBuilder.Field("itemname")
                    )
                    .withHighlightBuilder(new HighlightBuilder().preTags(preTag).postTags(postTag))
                    .withPageable(PageRequest.of(currentPage - 1, pageSize))
                    .build();
        }



        //总查询
        SearchHits<DmItemRowsEs> searchHits = elasticsearchRestTemplate.search(query,DmItemRowsEs.class);
        List<DmItemRowsEs> esList = new ArrayList<>();
        searchHits.getSearchHits().forEach(searchHit->{
            DmItemRowsEs dmItemRowsEs = searchHit.getContent();
            //高亮内容
            Map<String,List<String>> highlightFields = searchHit.getHighlightFields();

            /*searchHit.getContent().setItemName(highlightFields.get("itemname")==null ?
                        searchHit.getContent().getItemName():highlightFields.get("itemname").get(0))*/

            dmItemRowsEs.setItemName(
                highlightFields.get("itemName") == null ?
                        searchHit.getContent().getItemName()
                        :
                        highlightFields.get("itemName").get(0)
            );


            esList.add(dmItemRowsEs);
            //return searchHit.getContent();
        });//.collect(Collectors.toList());



        //处理页面分页
        DmItemRowsPageResponse<DmItemRowsEs> dmItemRowsPageResponse = new DmItemRowsPageResponse<>();
        if (currentPage!=null){
            dmItemRowsPageResponse.setCurrentPage(currentPage);
        }
        if (pageSize!=null){
            dmItemRowsPageResponse.setPageSize(pageSize);
        }
        dmItemRowsPageResponse.setPageCount(10);
        dmItemRowsPageResponse.setRows(esList);
        dmItemRowsPageResponse.setTotal((int) searchHits.getTotalHits());


        //给图片赋值
        dmItemRowsPageResponse.getRows().forEach(dmItemRowsEs -> {
            dmItemRowsEs.setImgUrl(dmImageClient.findItenPicByID(dmItemRowsEs.getId()).getImgUrl());
        });
        return dmItemRowsPageResponse;
    };

    /**
     * 猜你喜欢接口
     * @param itemTyp1Id
     * @return
     */
    public List<QueryItemList> queryItemList(Long itemTyp1Id){
        List<DmItem> dmItems = dmItemClient.postIndexSeniority(itemTyp1Id);

        List<QueryItemList> queryItemLists = new ArrayList<>();

        dmItems.forEach(es->{
            QueryItemList queryItemList = new QueryItemList();
            queryItemList.setId(es.getId());
            queryItemList.setItemName(es.getItemName());
            //剧院信息
            DmCinema dmCinema = dmCinemaClient.findById(es.getCinemaId());
            queryItemList.setAreaId(dmCinema.getAreaId());
            queryItemList.setAreaName(dmCinema.getAreaName());
            queryItemList.setAddress(dmCinema.getAddress());
            queryItemList.setStartData(es.getStartTime());
            queryItemList.setEndDate(es.getEndTime());
            //加入图片
            queryItemList.setImgUrl(dmImageClient.findItenPicByID(es.getId()).getImgUrl());
            queryItemList.setMinPrice(es.getMinPrice());
            queryItemLists.add(queryItemList);
        });

        return queryItemLists;
    }
}
